package com.tudouji.project.common;

import com.tudouji.framework.config.EncrypAES;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.ISysUserService;
import com.tudouji.project.wechat.service.impl.WechatServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Controller
@RequestMapping("/advice")
public class AdviceBackAction {

	@Autowired
	private ISysUserService userService;

	@Autowired
	private WechatServiceImpl wechatService;

	@RequestMapping(value = "/go")
	public String advicePage(HttpServletRequest request) {
		String openid = request.getParameter("openid");
		String url = request.getParameter("redirect_url");
		String code = request.getParameter("code");
		String id = request.getParameter("id");

		request.getSession().setAttribute("openid", openid);
		String token="";
		SysUser user = userService.selectUserByOpenid(openid);
		if (user != null) {
//			token= wechatService.login(user.getUserName(), EncrypAES.decrypt(user.getPassword()));
			token=wechatService.adviceAuthen(user.getUserName(), EncrypAES.decrypt(user.getPassword()));
//			result.get
			request.setAttribute("token", token);
		} else {
			log.info("------------通过Openid未查找到用户----");
		}
		url = url.replace('*', '#');
		if(!url.contains("?code=")){
			if (url.contains("?")) {
				url = url + "&code="+code+"&token="+token+"&id="+id;
			} else {
				url = url + "?code="+code+"&token="+token+"&id="+id;
			}
		}
		log.info("----------url-----"+url);
		request.setAttribute("url", url.trim());
		return "index";
	}

}
